<template>
  <div class="addModal">
    <el-dialog
        :title="isEdit ? '编辑区划':'新增区划'"
        :visible.sync="dialogVisible"
        width="600px">
      <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="区划名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入区划名称"></el-input>
        </el-form-item>
        <el-form-item label="区划代码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入区划代码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm()">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {Component, Vue, Prop, Ref} from 'vue-property-decorator';
import {addArea,updateArea} from "@/api/area";
import {validateForm} from "@/utils";

@Component
export default class AddModal extends Vue {
  @Ref('ruleForm') private ruleForm: any;
  @Prop()
  private isEdit!:any
  dialogVisible = false;
  formData = {
    name: '',
    parentId: '',
    code:'',
    parentName:'',
    orderNum:1,
    status:'0',
    id:''
  }
  rules = {
    name: [
      { required: true, message: '请输入区划名称', trigger: 'change' },
    ],
    code: [
      { required: true, message: '请输入区划代码', trigger: 'change' }
    ],
  }
  show(row){
    this.dialogVisible = true
    this.$nextTick(()=>{
      this.ruleForm.resetFields()
      if(!this.isEdit){
        this.formData.parentId = row.id
        this.formData.parentName = row.label
        this.formData.id = ""
        this.formData.name = ""
        this.formData.code = ""
      }else{
        this.formData.id = row.id
        this.formData.name = row.label
        this.formData.code = row.code
      }
    })
  }
  submitForm() {
    this.ruleForm.validate((valid) => {
      if (valid) {
        if (this.isEdit) {
          //编辑
          updateArea(this.formData).then((response: any) => {
            this.dialogVisible = false;
            this.$message.success(response.msg);
            this.$emit('success')
          }).catch((e) => {
            console.error(e);
            validateForm(e.data, this.ruleForm, this.rules);
          });
        } else {
          //新增
          addArea(this.formData).then((response: any) => {
            this.dialogVisible = false;
            this.$message.success(response.msg);
            this.$emit('success')
          }).catch((e) => {
            console.error(e);
            validateForm(e.data, this.ruleForm, this.rules);
          });
        }
      }
    });
  }
}
</script>
<style lang="scss" scoped>
</style>
